#coding=utf-8
'''
Created on 2015��2��14��

@author: wangpeng
'''
import urllib
import httplib
import json
import os
import os.path
import urlparse
import time
import random
#导入logging保存和输出文件模板 import logging_save
import logging_save
import re
import serial
import logging
import os
import monitor_cpumomory
class Volume(object):
    #构造函数定义，确定连接基本信息
    def __init__(self,conn=httplib.HTTPConnection('192.168.1.101'),headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/html"}):
        self.Connection=conn  
        self.Headers=headers
    #逐步增大音量设置      
    def adjust_up_volume(self):
        #print '***现在开始调节逐步增加音量测试***'
        set_volume(online_volumetest,0)
        logging_save.logging.info('***现在开始调节逐步增加音量测试***')
        for val in range(1,15):
            #设置音量为0
            self.Connection.request('GET', '/api/request-dev')
            getinformation=self.Connection.getresponse()
            readinformation=getinformation.read()
            getdeviceinfo=eval(readinformation)
            currentvolume=getdeviceinfo['volume']
            self.Connection.close()
            #print readinformation
            if currentvolume<15:
                postbody_volup='{"command":"key","value":4}'
                self.Connection.request('POST', '/api/key',postbody_volup,self.Headers)
                time.sleep(3)
                #print '调节之后的音量是：',currentvolume+1
                #使用logging_save.logging输出，console和txt同时保存
                logging_save.logging.info("调节之后的音量是："+str(currentvolume+1))
                self.Connection.close()   
                v0l_current=getvolume(self)
                #print '实际获取到的音量是：',v0l_current
                logging_save.logging.info("实际获取到的音量是："+str(v0l_current))
                
                #检测CPU值
                monitor_cpumomory.detectmomoerycpu()
                
                time.sleep(5)
                
                if currentvolume==15:
                    postbody_volup='{"command":"key","value":4}'
                    self.Connection.request('POST', '/api/key',postbody_volup,self.Headers)
                    
                    #print '调节之后的音量是',currentvolume
                    logging_save.logging.info("调节之后的音量是："+str(currentvolume))
                    self.Connection.close()   
                    #print '实际获取到的音量是',v0l_current
                    logging_save.logging.info("实际获取到的音量是："+str(v0l_current))
                    time.sleep(3)
                    
                    monitor_cpumomory
                
                if currentvolume+1!=v0l_current:
                    logging_save.logging.warning('FAIL,FAIL,FAIL,实际音量和调节不一致')
                    #print 'Fail,实际音量和调节不一致'
                    
                    monitor_cpumomory
            else:
                logging_save.logging.info('the volume is the max already')
                #print 'the volume is the max already'
                logging_save.logging.info("增加之后音量是："+str(currentvolume))
                #print '增加之后音量是',currentvolume
                volmax_current=getvolume(self)
                logging_save.logging.info("实际获取到的音量是："+str(volmax_current))
                #print '实际获取到的音量是',volmax_current
                if currentvolume!=volmax_current:
                    logging_save.logging.warning('FAIL,FAIL,FAIL,实际音量和调节不一致')
                    #print '调节之后音量和实际获取音量不一致'
                time.sleep(3)       
                
                #检测CPU值
                monitor_cpumomory.detectmomoerycpu()
                
    #声音递减测试
    def adjust_down_volume(self):
        #设置音量为15最大值
        set_volume(online_volumetest,15)
        logging_save.logging.info('***现在开始调节逐步减少音量测试***')
        #print '***现在开始调节逐步减少音量测试***'
        for val in range(16):
            self.Connection.request('GET', '/api/request-dev')
            getinformation=self.Connection.getresponse()
            readinformation=getinformation.read()
            getdeviceinfo=eval(readinformation)
            currentvolume=getdeviceinfo['volume']
            self.Connection.close()
            if currentvolume>0:
                postbody_voldown='{"command":"key","value":5}'
                self.Connection.request('POST', '/api/key',postbody_voldown,self.Headers)
                
                logging_save.logging.info("调节之后的音量是："+str(currentvolume-1))
                #print '调节之后的音量是：',currentvolume-1
                self.Connection.close()   
                v0l_current=getvolume(self)
                logging_save.logging.info("实际获取到的音量是："+str(v0l_current))
                
                monitor_cpumomory.detectmomoerycpu()
                
                #print '实际获取到的音量是：',v0l_current
                time.sleep(3)
                if currentvolume==0:
                    postbody_voldown='{"command":"key","value":5}'
                    self.Connection.request('POST', '/api/key',postbody_voldown,self.Headers)
                    logging_save.logging.info("调节之后的音量是："+str(currentvolume))
                    
                    #print '调节之后的音量是',currentvolume
                    self.Connection.close()   
                    logging_save.logging.info("实际获取到的音量是："+str(getvolume()))
                    
                    monitor_cpumomory.detectmomoerycpu()

                    #print '实际获取到的音量是',getvolume()     
                    time.sleep(3) 
                    
                if currentvolume-1!=getvolume(self):
                    logging_save.logging.warning('FAIL,FAIL,FAIL,实际音量和调节不一致')
                    #print 'Fail,实际音量和调节不一致'
                    
            else:
                logging_save.logging.info('***the volume is the min already***')
                #print 'the volume is the min already'
                logging_save.logging.info("调节之后音量是："+str(currentvolume))
                #print '调节之后音量是',currentvolume
                volmin_current=getvolume(self)
                logging_save.logging.info("实际获取到的音量是："+str(volmin_current))
                #print '实际获取到的音量是',volmin_current
                time.sleep(5)
                if currentvolume!=volmin_current:
                    logging_save.logging.warning('FAIL,FAIL,FAIL,实际音量和调节不一致')
                    #print '调节之后音量和实际获取音量不一致'
                    time.sleep(5)   
                      
                monitor_cpumomory             
    #设置音量未mute和解mute，1.先提前提高下音量，确保当前音量不是0  2.如果当前音量已经是0，则mute再反馈是否未音量               
    def mute(self):
        logging_save.logging.info('***现在开始设置静音测试***')
        for val in range(16):
            postbody_volume={"command":"vol-setting","value":random.randint(1,15)}
        #设置一个随机音量
            playback=json.dumps(postbody_volume)
            self.Connection.request('POST', '/api/vol-setting',playback,self.Headers) 
            self.Connection.close()
            currentvolume =getvolume(self)
            logging_save.logging.info("当前音量："+str(currentvolume ))
            #print '当前音量:',currentvolume  
            time.sleep(3)
            
            
            
        #需要实时监测音量值，如果发现不是的话，则需要报错
            postbody_volume='{"command":"vol-setting","value":0}'
            self.Connection.request('POST', '/api/vol-setting',postbody_volume,self.Headers) 
            self.Connection.close()
            vol_0=getvolume(self)
        #静音状态
            logging_save.logging.info("机器已经进入静音状态~~~~~~~："+str(vol_0))
            #print '静音状态~~~~~~~：',vol_0   
            time.sleep(3)
        
        #设置一个随机音量
            self.Connection.request('POST', '/api/vol-setting',playback,self.Headers) 
            self.Connection.close()
            vol_again=getvolume(self)
            logging_save.logging.info("静音状态~~~~~~~："+str(vol_again))
            #print '解锁状态~~~~~~~：',vol_again
            time.sleep(3)
        
            
            
            #函数暂时无法判定，因为设置为mute之后，实质值并没有变化
            if vol_0==0:
                logging_save.logging.info('okay，已经处于静音状态')
                #print 'okay，已经处于静音状态'
                time.sleep(3)   
            else:
                logging_save.logging.warning('FAIL,FAIL,FAIL,未处于静音状态')
                #print 'WARNING，WARING,WARNING,未处于静音状态'
                time.sleep(3)
                
                
            monitor_cpumomory.detectmomoerycpu() 
            
    def randdomtest(self):
        logging_save.logging.info('***现在开始随机设置音量测试***')
        for val in range(1,16):
            postbody_volume_random={"command":"vol-setting","value":random.randint(0,15)}
            logging_save.logging.info("打算设置的音量值为:："+str(postbody_volume_random["value"]))
            
            #print '打算设置的音量值为:   ', postbody_volume_random["value"]
            time.sleep(3)
        #设置一个随机音量
            playback=json.dumps(postbody_volume_random)
            self.Connection.request('POST', '/api/vol-setting',playback,self.Headers)
            self.Connection.close()
            vol_current=getvolume(self)
            
            logging_save.logging.info("设置之后的音量值为:："+str(vol_current))
            #print '设置之后的音量值为：   ',vol_current
            time.sleep(3)
            
        
            if postbody_volume_random["value"]==vol_current:
                logging_save.logging.info('打算设置的音量和实际得到音量一致')
                #print '打算设置的音量和实际得到音量一致'
            
            else:
                logging_save.logging.warning('FAIL,FAIL,FAIL,未处于静音状态')
                #print 'FAIL,FAIL,FAIL,打算设置的音量和实际得到音量 不一致'
                
        monitor_cpumomory.detectmomoerycpu()
        
    def quickadust_volume(self):
        logging_save.logging.info('***现在开始快速的调节音量***')
        for volumetest in range(3):
        #初始音量为0
            set_volume(online_volumetest,0)
        #声音从最低到最高依次跨快速增加
            for val in range(1,16):
                set_volume(online_volumetest,val)
                time.sleep(0.3)
            
            time.sleep(2)
            
            if getvolume(self)==15:
                logging_save.logging.info("up快速调节音量成功")
                
            else:
                logging_save.logging.warning('FAIL,FAIL,FAIL,up快速调节音量失败')
        #设置当前音量为最大值
            time.sleep(2)
            
            set_volume(online_volumetest,15)
        #声音从最低到最高依次慢速增加
            for val in reversed(range(0,16)):
                set_volume(online_volumetest,val)
                time.sleep(0.1)
                
            time.sleep(2)
            if getvolume(self)==0:
                logging_save.logging.info("down快速调节音量成功")
            else:
                logging_save.logging.warning('FAIL,FAIL,FAIL,up快速调节音量失败')   
            time.sleep(2)
            
            monitor_cpumomory.detectmomoerycpu()
            
    def slowadjust_volume(self):
        logging_save.logging.info('***现在开始慢速的的调节音量***')
        for volumetest in range(3):
        #初始音量为0
            set_volume(online_volumetest,0)
        #声音从最低到最高依次跨快速增加
            for val in range(1,16):
                set_volume(online_volumetest,val)
                time.sleep(2)
            
            time.sleep(2)
            
            if getvolume(self)==15:
                logging_save.logging.info("up慢速调节音量成功")
                
            else:
                logging_save.logging.warning('FAIL,FAIL,FAIL,up慢速调节音量失败')
        
        #设置当前音量为最大值
            time.sleep(2)
            set_volume(online_volumetest,15)
        #声音从最低到最高依次慢速增加
            for val in reversed(range(0,16)):
                set_volume(online_volumetest,val)
                time.sleep(2)
                
            time.sleep(2)
            if getvolume(self)==0:
                logging_save.logging.info("down慢速调节音量成功")
                
            else:
                logging_save.logging.warning('FAIL,FAIL,FAIL,down慢速调节音量失败')   
                
            time.sleep(2)
           
            monitor_cpumomory.detectmomoerycpu()
            
    def poweronoff(self):
        logging_save.logging.info("关机前音量值为"+str(getvolume(self)))
        volume_before=getvolume(self)
        logging_save.logging.info("现在进入关机状态，等待10钟之后机器再开机")
        os.system(r'D:\power\power.exe com3 pw_off 6')
        time.sleep(10)
        os.system(r'D:\power\power.exe com3 pw_on 7')
        logging_save.logging.info("开机中，请耐心等待~~~~")
        time.sleep(60)
        logging_save.logging.info("机器进入开机状态，此时音量值为："+str(getvolume(self)))
        volume_after=getvolume(self)
        
        if volume_before==volume_after:
            logging_save.logging.info("开机前和关机前音量保持一致")
        
        else:
            logging_save.logging.warning('FAIL,FAIL,FAIL,音量已经变化')
        
        time.sleep(1)
        monitor_cpumomory.detectmomoerycpu()
    
    #暂时无法使用，因为reboot之后系统直接再连接上            
    '''         
    def reboot_volume(self):
        logging_save.logging.info('***现在开始开关机之后测试音量值是否保持一致，不会变化***')
        for val in range(1,15):
            self.Connection.request('GET', '/api/request-dev')
            getinformation=self.Connection.getresponse()
            readinformation=getinformation.read()
            getdeviceinfo=eval(readinformation)
            currentvolume=getdeviceinfo['volume']
            self.Connection.close()
            #logging_save.logging.info("关机之前音量是:",str(currentvolume))
            print '关机之前音量是：',currentvolume
            #发送串口命令：reboot重启，判断重启之后音量是否变化
            self.serialconnection.write('reboot\n')
            time.sleep(10)
            #readinfo=self.Connection.read(100)
            #print readinfo,
            self.serialconnection.close()
            time.sleep(100)
            v0l_current=getvolume(self)
            
            if currentvolume==v0l_current:
                #logging_save.logging.info("开机和关机音量保持一致")
                print '开机和关机音量保持一致：',currentvolume
            
            
            
            if currentvolume<15:
                postbody_volup='{"command":"key","value":4}'
                self.Connection.request('POST', '/api/key',postbody_volup,self.Headers)
                time.sleep(5)
                #print '调节之后的音量是：',currentvolume+1
                #使用logging_save.logging输出，console和txt同时保存
                logging_save.logging.info("调节之后的音量是："+str(currentvolume+1))
                self.Connection.close()   
                v0l_current=getvolume(self)
                #print '实际获取到的音量是：',v0l_current
                logging_save.logging.info("实际获取到的音量是："+str(v0l_current))
                time.sleep(5)
                if currentvolume==15:
                    postbody_volup='{"command":"key","value":4}'
                    self.Connection.request('POST', '/api/key',postbody_volup,self.Headers)
                    
                    #print '调节之后的音量是',currentvolume
                    logging_save.logging.info("调节之后的音量是："+str(currentvolume))
                    self.Connection.close()   
                    #print '实际获取到的音量是',v0l_current
                    logging_save.logging.info("实际获取到的音量是："+str(v0l_current))
                    time.sleep(10)
                
                if currentvolume+1!=v0l_current:
                    
                    logging_save.logging.warning('FAIL,FAIL,FAIL,实际音量和调节不一致')
                    #print 'Fail,实际音量和调节不一致'
                    
            else:
                logging_save.logging.info('the volume is the max already')
                #print 'the volume is the max already'
                logging_save.logging.info("增加之后音量是："+str(currentvolume))
                #print '增加之后音量是',currentvolume
                volmax_current=getvolume(self)
                logging_save.logging.info("实际获取到的音量是："+str(volmax_current))
                #print '实际获取到的音量是',volmax_current
            
                if currentvolume!=volmax_current:
                    
                    logging_save.logging.warning('FAIL,FAIL,FAIL,实际音量和调节不一致')
                    #print '调节之后音量和实际获取音量不一致'
                time.sleep(5)       
          
     '''    
#设置随机音量 
def set_volume(self,setvolume):
    postbody_setvolume={"command":"vol-setting","value":setvolume}
    postjson=json.dumps(postbody_setvolume)
    self.Connection.request('POST', '/api/vol-setting',postjson,self.Headers)
    logging_save.logging.info("音量已经设置为："+str(setvolume))
    self.Connection.close()   
     
#获取当前音量
def getvolume(self):
    self.Connection.request('GET', '/api/request-dev')
    getinformation=self.Connection.getresponse()
    readinformation=getinformation.read()
    getdeviceinfo=eval(readinformation)
    currentvolume=getdeviceinfo['volume']
    return currentvolume
    self.Connection.close()   
  
class kaola_music(Volume):
    def playurl_kaola(self):
        postbody={"command":"pb-start-url",
                "value": "http://image.kaolafm.net/mz/audios/201408/e6191927-1509-4cbd-b90b-0c741373ee31.mp3?appid=marxc4577&deviceid=100000029165298&audioid=1000000326510", 
                "title":"", 
                "artist":"",
                "album": "", 
                "mtype":5
                }
        PlaybackURLJson=json.dumps(postbody)
        self.Connection.request('POST', '/api/pb-start-url',PlaybackURLJson,self.Headers)
        self.Connection.close()
        print '此时播放已经切换到虾米音乐。。。。'
        time.sleep(5)

class ximalaya_music(Volume):
    def playurl_ximalaya(self):
        postbody={"command":"pb-start-url",
                  "value": "http://fdfs.xmcdn.com/group4/M04/79/36/wKgDs1PGpw-gd7xFAEqrTYQzId8968.mp3", 
                  "title":"", 
                  "artist":"",
                  "album": "", 
                  "mtype":8
        }
        PlaybackURLJson=json.dumps(postbody)
        self.Connection.request('POST', '/api/pb-start-url',PlaybackURLJson,self.Headers)    
        self.Connection.close()
        print '此时播放已经切换到喜马拉雅音乐。。。。'
        time.sleep(5)



class local_music(Volume):       
    def playurl_local_music(self):
        postbody={"command":"pb-start-url",
                  "value":'http://192.168.0.181/wangpeng/1.mp3', 
                  "title":"", 
                  "artist":"",
                  "album": "", 
                  "mtype":5
        }
        PlaybackURLJson=json.dumps(postbody)
        self.Connection.request('POST','/api/pb-start-url',PlaybackURLJson,self.Headers)
        self.Connection.close()
        print '此时播放本地电脑歌曲。。。。'
        
#但是怎么推送app本地歌曲
        time.sleep(5)


if __name__=='__main__':   
    online_volumetest=Volume()
    
    #实例化
    logging_save.logging.info("现在开始播放的是首页虾米在线音乐")
    online_volumetest.adjust_up_volume()
    time.sleep(1)
    online_volumetest.adjust_down_volume()
    time.sleep(1)
    online_volumetest.mute()
    time.sleep(1)
    online_volumetest.randdomtest()
    time.sleep(1)
    online_volumetest.quickadust_volume()
    time.sleep(1)
    online_volumetest.slowadjust_volume()
    time.sleep(1)
    online_volumetest.poweronoff()
    time.sleep(1)
    
    logging_save.logging.info("首页音乐播放结束")
    #播放考拉音乐
    logging_save.logging.info("现在开始播放的是考拉在线音乐")
    kaola=kaola_music()
    time.sleep(1)
    kaola.playurl_kaola()
    time.sleep(1)
    kaola.adjust_up_volume()
    time.sleep(1)
    kaola.adjust_down_volume()
    time.sleep(1)
    kaola.mute()
    time.sleep(1)
    kaola.randdomtest()
    time.sleep(1)
    kaola.quickadust_volume()
    time.sleep(1)
    kaola.slowadjust_volume()
    time.sleep(1)
    kaola.poweronoff()
    logging_save.logging.info("考拉音乐播放结束")
    time.sleep(1)
    
    logging_save.logging.info("现在开始播放的是喜马拉雅音乐")
    time.sleep(1)
    ximalaya=ximalaya_music()
    time.sleep(1)
    ximalaya.playurl_ximalaya()
    time.sleep(1)
    ximalaya.adjust_up_volume()
    time.sleep(1)
    ximalaya.adjust_down_volume()
    time.sleep(1)
    ximalaya.mute()
    time.sleep(1)
    ximalaya.randdomtest()
    time.sleep(1)
    ximalaya.quickadust_volume()
    time.sleep(1)
    ximalaya.slowadjust_volume()
    time.sleep(1)
    ximalaya.poweronoff()
    logging_save.logging.info("喜马拉雅播放结束")
    time.sleep(1)
    logging_save.logging.info("现在开始播放当地音乐")
    local=local_music()
    time.sleep(1)
    local.playurl_local_music()
    time.sleep(1)
    local.adjust_up_volume()
    time.sleep(1)
    local.adjust_down_volume()
    time.sleep(1)
    local.mute()
    time.sleep(1)
    local.randdomtest()
    time.sleep(1)
    local.poweronoff()
    logging_save.logging.info("当地音乐播放结束")
  
'''
filelist=open('F:\\mtktool_ver2.47.03.04\\MtkLog\\3.txt','r')
ftest=open('C:\\Users\\403720\\workspace\\PythonLearn1\\src\\huawei_musi\\myapp_2.txt','r')
#warning_number=ftest.read().count('WARNING')
#print warning_number
#ftest.close()
#ftest=open('C:\\Users\\403720\\workspace\\PythonLearn1\\src\\huawei_musi\\myapp_2.txt','r')
def bug_information():
    #print warning_number
    for eachline_bug in ftest:
        ftest_search=r"WARNING"
        test=re.findall(ftest_search,eachline_bug)
        print test,
        if test:
            print '>>'
            for eachline_log in filelist:
                if eachline_log[1:11]==eachline_bug[0:10]:
                    #print eachline_log[0:12]
                    #print eachline_log,
                    #统计txt出现warning的次数，方便后续做For循环
                    mkdirfile=open('D:\\bug.txt','a+')
                    mkdirfile.write(eachline_log)
        else:
            pass
        
        
bug_information()
filelist.close()
ftest.close()
'''